1   /*
2    * Copyright (C) 2011 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.math;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  import static com.google.common.math.MathPreconditions.checkNoOverflow;
21  import static com.google.common.math.MathPreconditions.checkNonNegative;
22  import static com.google.common.math.MathPreconditions.checkPositive;
23  import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
24  import static java.lang.Math.abs;
25  import static java.lang.Math.min;
26  import static java.math.RoundingMode.HALF_EVEN;
27  import static java.math.RoundingMode.HALF_UP;
28  
29  import com.google.common.annotations.GwtCompatible;
30  import com.google.common.annotations.VisibleForTesting;
31  
32  import java.math.RoundingMode;
33  
34  /**
35   * A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
36   * named analogously to their {@code BigInteger} counterparts.
37   *
38   * <p>The implementations of many methods in this class are based on material from Henry S. Warren,
39   * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
40   *
41   * <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in
42   * {@link LongMath} and {@link BigIntegerMath} respectively.  For other common operations on
43   * {@code int} values, see {@link com.google.common.primitives.Ints}.
44   *
45   * @author Louis Wasserman
46   * @since 11.0
47   */
48  @GwtCompatible(emulated = true)
49  public final class IntMath {
50    // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
51  
52    /**
53     * Returns {@code true} if {@code x} represents a power of two.
54     *
55     * <p>This differs from {@code Integer.bitCount(x) == 1}, because
56     * {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
57     * of two.
58     */
59    public static boolean isPowerOfTwo(int x) {
60      return x > 0 & (x & (x - 1)) == 0;
61    }
62    
63    /**
64     * Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into
65     * a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if
66     * narrowly) faster than the straightforward ternary expression.
67     */
68    @VisibleForTesting
69    static int lessThanBranchFree(int x, int y) {
70      // The double negation is optimized away by normal Java, but is necessary for GWT
71      // to make sure bit twiddling works as expected.
72      return ~~(x - y) >>> (Integer.SIZE - 1);
73    }
74  
75    /**
76     * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
77     *
78     * @throws IllegalArgumentException if {@code x <= 0}
79     * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
80     *         is not a power of two
81     */
82    @SuppressWarnings("fallthrough")
83    // TODO(kevinb): remove after this warning is disabled globally
84    public static int log2(int x, RoundingMode mode) {
85      checkPositive("x", x);
86      switch (mode) {
87        case UNNECESSARY:
88          checkRoundingUnnecessary(isPowerOfTwo(x));
89          // fall through
90        case DOWN:
91        case FLOOR:
92          return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
93  
94        case UP:
95        case CEILING:
96          return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
97  
98        case HALF_DOWN:
99        case HALF_UP:
100       case HALF_EVEN:
101         // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
102         int leadingZeros = Integer.numberOfLeadingZeros(x);
103         int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
104           // floor(2^(logFloor + 0.5))
105         int logFloor = (Integer.SIZE - 1) - leadingZeros;
106         return logFloor + lessThanBranchFree(cmp, x);
107 
108       default:
109         throw new AssertionError();
110     }
111   }
112 
113   /** The biggest half power of two that can fit in an unsigned int. */
114   @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
115 
116   private static int log10Floor(int x) {
117     /*
118      * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
119      *
120      * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
121      * we can narrow the possible floor(log10(x)) values to two.  For example, if floor(log2(x))
122      * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
123      */
124     int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
125     /*
126      * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
127      * lower of the two possible values, or y - 1, otherwise, we want y.
128      */
129     return y - lessThanBranchFree(x, powersOf10[y]);
130   }
131 
132   // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
133   @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {9, 9, 9, 8, 8, 8,
134     7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0};
135 
136   @VisibleForTesting static final int[] powersOf10 = {1, 10, 100, 1000, 10000,
137     100000, 1000000, 10000000, 100000000, 1000000000};
138 
139   // halfPowersOf10[i] = largest int less than 10^(i + 0.5)
140   @VisibleForTesting static final int[] halfPowersOf10 =
141       {3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
142 
143   private static int sqrtFloor(int x) {
144     // There is no loss of precision in converting an int to a double, according to
145     // http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
146     return (int) Math.sqrt(x);
147   }
148 
149   /**
150    * Returns the result of dividing {@code p} by {@code q}, rounding using the specified
151    * {@code RoundingMode}.
152    *
153    * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
154    *         is not an integer multiple of {@code b}
155    */
156   @SuppressWarnings("fallthrough")
157   public static int divide(int p, int q, RoundingMode mode) {
158     checkNotNull(mode);
159     if (q == 0) {
160       throw new ArithmeticException("/ by zero"); // for GWT
161     }
162     int div = p / q;
163     int rem = p - q * div; // equal to p % q
164 
165     if (rem == 0) {
166       return div;
167     }
168 
169     /*
170      * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
171      * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
172      * p / q.
173      *
174      * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
175      */
176     int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
177     boolean increment;
178     switch (mode) {
179       case UNNECESSARY:
180         checkRoundingUnnecessary(rem == 0);
181         // fall through
182       case DOWN:
183         increment = false;
184         break;
185       case UP:
186         increment = true;
187         break;
188       case CEILING:
189         increment = signum > 0;
190         break;
191       case FLOOR:
192         increment = signum < 0;
193         break;
194       case HALF_EVEN:
195       case HALF_DOWN:
196       case HALF_UP:
197         int absRem = abs(rem);
198         int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
199         // subtracting two nonnegative ints can't overflow
200         // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
201         if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
202           increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
203         } else {
204           increment = cmpRemToHalfDivisor > 0; // closer to the UP value
205         }
206         break;
207       default:
208         throw new AssertionError();
209     }
210     return increment ? div + signum : div;
211   }
212 
213   /**
214    * Returns {@code x mod m}, a non-negative value less than {@code m}.
215    * This differs from {@code x % m}, which might be negative.
216    *
217    * <p>For example:<pre> {@code
218    *
219    * mod(7, 4) == 3
220    * mod(-7, 4) == 1
221    * mod(-1, 4) == 3
222    * mod(-8, 4) == 0
223    * mod(8, 4) == 0}</pre>
224    *
225    * @throws ArithmeticException if {@code m <= 0}
226    * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
227    *      Remainder Operator</a>
228    */
229   public static int mod(int x, int m) {
230     if (m <= 0) {
231       throw new ArithmeticException("Modulus " + m + " must be > 0");
232     }
233     int result = x % m;
234     return (result >= 0) ? result : result + m;
235   }
236 
237   /**
238    * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
239    * {@code a == 0 && b == 0}.
240    *
241    * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
242    */
243   public static int gcd(int a, int b) {
244     /*
245      * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
246      * gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
247      * isn't an int.
248      */
249     checkNonNegative("a", a);
250     checkNonNegative("b", b);
251     if (a == 0) {
252       // 0 % b == 0, so b divides a, but the converse doesn't hold.
253       // BigInteger.gcd is consistent with this decision.
254       return b;
255     } else if (b == 0) {
256       return a; // similar logic
257     }
258     /*
259      * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
260      * This is >40% faster than the Euclidean algorithm in benchmarks.
261      */
262     int aTwos = Integer.numberOfTrailingZeros(a);
263     a >>= aTwos; // divide out all 2s
264     int bTwos = Integer.numberOfTrailingZeros(b);
265     b >>= bTwos; // divide out all 2s
266     while (a != b) { // both a, b are odd
267       // The key to the binary GCD algorithm is as follows:
268       // Both a and b are odd.  Assume a > b; then gcd(a - b, b) = gcd(a, b).
269       // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
270 
271       // We bend over backwards to avoid branching, adapting a technique from
272       // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
273 
274       int delta = a - b; // can't overflow, since a and b are nonnegative
275 
276       int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
277       // equivalent to Math.min(delta, 0)
278 
279       a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
280       // a is now nonnegative and even
281 
282       b += minDeltaOrZero; // sets b to min(old a, b)
283       a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
284     }
285     return a << min(aTwos, bTwos);
286   }
287 
288   /**
289    * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
290    *
291    * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
292    */
293   public static int checkedAdd(int a, int b) {
294     long result = (long) a + b;
295     checkNoOverflow(result == (int) result);
296     return (int) result;
297   }
298 
299   /**
300    * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
301    *
302    * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
303    */
304   public static int checkedSubtract(int a, int b) {
305     long result = (long) a - b;
306     checkNoOverflow(result == (int) result);
307     return (int) result;
308   }
309 
310   /**
311    * Returns the product of {@code a} and {@code b}, provided it does not overflow.
312    *
313    * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
314    */
315   public static int checkedMultiply(int a, int b) {
316     long result = (long) a * b;
317     checkNoOverflow(result == (int) result);
318     return (int) result;
319   }
320 
321   /**
322    * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
323    *
324    * <p>{@link #pow} may be faster, but does not check for overflow.
325    *
326    * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
327    *         {@code int} arithmetic
328    */
329   public static int checkedPow(int b, int k) {
330     checkNonNegative("exponent", k);
331     switch (b) {
332       case 0:
333         return (k == 0) ? 1 : 0;
334       case 1:
335         return 1;
336       case (-1):
337         return ((k & 1) == 0) ? 1 : -1;
338       case 2:
339         checkNoOverflow(k < Integer.SIZE - 1);
340         return 1 << k;
341       case (-2):
342         checkNoOverflow(k < Integer.SIZE);
343         return ((k & 1) == 0) ? 1 << k : -1 << k;
344       default:
345         // continue below to handle the general case
346     }
347     int accum = 1;
348     while (true) {
349       switch (k) {
350         case 0:
351           return accum;
352         case 1:
353           return checkedMultiply(accum, b);
354         default:
355           if ((k & 1) != 0) {
356             accum = checkedMultiply(accum, b);
357           }
358           k >>= 1;
359           if (k > 0) {
360             checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
361             b *= b;
362           }
363       }
364     }
365   }
366 
367   @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
368 
369   /**
370    * Returns {@code n!}, that is, the product of the first {@code n} positive
371    * integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
372    * result does not fit in a {@code int}.
373    *
374    * @throws IllegalArgumentException if {@code n < 0}
375    */
376   public static int factorial(int n) {
377     checkNonNegative("n", n);
378     return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
379   }
380 
381   private static final int[] factorials = {
382       1,
383       1,
384       1 * 2,
385       1 * 2 * 3,
386       1 * 2 * 3 * 4,
387       1 * 2 * 3 * 4 * 5,
388       1 * 2 * 3 * 4 * 5 * 6,
389       1 * 2 * 3 * 4 * 5 * 6 * 7,
390       1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
391       1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
392       1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
393       1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
394       1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
395 
396   // binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
397   @VisibleForTesting static int[] biggestBinomials = {
398     Integer.MAX_VALUE,
399     Integer.MAX_VALUE,
400     65536,
401     2345,
402     477,
403     193,
404     110,
405     75,
406     58,
407     49,
408     43,
409     39,
410     37,
411     35,
412     34,
413     34,
414     33
415   };
416 
417   /**
418    * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
419    * negative infinity. This method is overflow resilient.
420    *
421    * @since 14.0
422    */
423   public static int mean(int x, int y) {
424     // Efficient method for computing the arithmetic mean.
425     // The alternative (x + y) / 2 fails for large values.
426     // The alternative (x + y) >>> 1 fails for negative values.
427     return (x & y) + ((x ^ y) >> 1);
428   }
429 
430   private IntMath() {}
431 }
432